<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号：" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称：" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否实名认证：" prop="isVerified" label-width="150px">
        <el-input
          v-model="queryParams.isVerified"
          placeholder="请输入是否实名认证"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否VIP：" prop="isVip" label-width="150px">
        <el-input
          v-model="queryParams.isVip"
          placeholder="请输入是否VIP"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <br>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['user:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['user:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['user:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['user:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100px" />
      <el-table-column label="手机号" align="center" prop="phone" width="100px"/>
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="性别" align="center" prop="gender" >
        <template #default="scope">
          <el-tag v-if="scope.row.gender === 1">男</el-tag>
          <el-tag v-else-if="scope.row.gender === 2">女</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像URL" align="center" prop="avatarUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.avatarUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="粉丝数" align="center" prop="fan" />
      <el-table-column label="被关注总数" align="center" prop="countFollow" width="150px"/>
      <el-table-column label="被赞总数" align="center" prop="countLike" />
      <el-table-column label="用户角色" align="center" prop="userRole">
        <template #default="scope">
          <el-tag v-if="scope.row.userRole === 1" type="info">普通用户</el-tag>
          <el-tag v-else-if="scope.row.userRole === 2" type="success">红娘</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册来源" align="center" prop="registerSource">
        <template #default="scope">
          <el-tag v-if="scope.row.registerSource === 1">手机号</el-tag>
          <el-tag v-else-if="scope.row.registerSource === 2">微信</el-tag>
          <el-tag v-else>QQ</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="registerTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="lastLoginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" align="center" prop="lastLoginIp"  width="150px"/>
      <el-table-column label="账号状态" align="center" prop="accountStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.accountStatus === 0">冻结</el-tag>
          <el-tag v-else-if="scope.row.accountStatus === 1">正常</el-tag>
          <el-tag v-else>注销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否实名认证" align="center" prop="isVerified" width="150px">
        <template #default="scope">
          <el-tag v-if="scope.row.isVerified === 0">未认证</el-tag>
          <el-tag v-else-if="scope.row.isVerified === 1">已认证</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否VIP" align="center" prop="isVip" >
        <template #default="scope">
          <el-tag v-if="scope.row.isVip === 0">否</el-tag>
          <el-tag v-else-if="scope.row.isVip === 1">是</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="VIP过期时间" align="center" prop="vipExpireTime" width="180">
        <template #default="scope">
          <span v-if="scope.row.vipExpireTime">{{ parseTime(scope.row.vipExpireTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else style="color: #909399;">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span v-if="scope.row.updatedAt">
            {{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else style="color: #909399;">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleViewMatchmaker(scope.row)" v-if="scope.row.userRole === 2" title="查看红娘详细信息">
            <el-icon><View /></el-icon>
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['user:user:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['user:user:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改管理用户对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body >
      <el-form ref="userRef" :model="form" :rules="rules">
        <!-- 用户基本信息表格 -->
        <el-table :data="userInfoList" class="vertical-layout-table" :show-header="false" style="border: 1px solid #ebeef5; border-radius: 6px;">
          <el-table-column label="字段" width="120" align="right" class-name="field-label-column">
            <template #default="scope">
              <div style="font-weight: 500; color: #606266; padding-right: 10px;">{{ getUserFieldLabel(scope.$index) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="值" min-width="300" class-name="field-value-column">
            <template #default="scope">
              <!-- 手机号 -->
              <div v-if="scope.$index === 0">
                <el-input v-model="form.phone" placeholder="请输入手机号" @input="handlePhoneChange" @blur="validatePhone" />
                <div v-if="phoneValidationMessage" :class="phoneValidationClass" style="font-size: 12px; margin-top: 4px;">
                  {{ phoneValidationMessage }}
                </div>
              </div>
              <!-- 密码 -->
              <div v-else-if="scope.$index === 1">
                <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password @blur="validatePassword" />
                <div v-if="passwordValidationMessage" :class="passwordValidationClass" style="font-size: 12px; margin-top: 4px;">
                  {{ passwordValidationMessage }}
                </div>
              </div>
              <!-- 昵称 -->
              <div v-else-if="scope.$index === 2">
                <el-input v-model="form.nickname" placeholder="请输入昵称" @blur="validateNickname" />
                <div v-if="nicknameValidationMessage" :class="nicknameValidationClass" style="font-size: 12px; margin-top: 4px;">
                  {{ nicknameValidationMessage }}
                </div>
              </div>
              <!-- 性别 -->
              <el-radio-group v-else-if="scope.$index === 3" v-model="form.gender">
                <el-radio label="0">未知</el-radio>
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
              <!-- 出生日期 -->
              <el-date-picker v-else-if="scope.$index === 4" v-model="form.birthDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择出生日期" style="width: 100%" />
              <!-- 头像URL -->
              <div v-else-if="scope.$index === 5">
                <image-upload v-model="form.avatarUrl" :limit="1" :file-size="2" :is-show-tip="false"/>
                <div class="upload-tip">
                  <span style="color: #909399; font-size: 12px;">
                    请上传用户头像，仅支持1张图片，大小不超过2MB
                  </span>
                </div>
              </div>
              <!-- 用户角色 -->
              <el-radio-group v-else-if="scope.$index === 6" v-model="form.userRole" @change="handleUserRoleChange">
                <el-radio label="1">普通用户</el-radio>
                <el-radio label="2">红娘</el-radio>
              </el-radio-group>
              <!-- 注册来源 -->
              <el-radio-group v-else-if="scope.$index === 7" v-model="form.registerSource">
                <el-radio label="1">手机号</el-radio>
                <el-radio label="2">微信</el-radio>
                <el-radio label="3">QQ</el-radio>
              </el-radio-group>
              <!-- 第三方平台ID -->
              <el-input v-else-if="scope.$index === 8 && form.registerSource !== '1'" v-model="form.openId" placeholder="请输入第三方平台ID" />
              <span v-else-if="scope.$index === 8 && form.registerSource === '1'" style="color: #909399;">手机号注册无需填写</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 修改时显示用户状态信息 -->
        <div v-if="form.userId">
          <el-divider content-position="center" style="margin-top: 30px;">用户状态信息</el-divider>
          <el-table :data="userStatusList" class="vertical-layout-table" :show-header="false" style="border: 1px solid #ebeef5; border-radius: 6px;">
            <el-table-column label="字段" width="120" align="right" class-name="field-label-column">
              <template #default="scope">
                <div style="font-weight: 500; color: #606266; padding-right: 10px;">{{ getUserStatusFieldLabel(scope.$index) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="值" min-width="300" class-name="field-value-column">
              <template #default="scope">
                <!-- 账号状态 -->
                <el-radio-group v-if="scope.$index === 0" v-model="form.accountStatus">
                  <el-radio label="0">冻结</el-radio>
                  <el-radio label="1">正常</el-radio>
                  <el-radio label="2">注销</el-radio>
                </el-radio-group>
                <!-- 是否实名认证 -->
                <el-radio-group v-else-if="scope.$index === 1" v-model="form.isVerified">
                  <el-radio label="0">否</el-radio>
                  <el-radio label="1">是</el-radio>
                </el-radio-group>
                <!-- 是否VIP -->
                <el-radio-group v-else-if="scope.$index === 2" v-model="form.isVip">
                  <el-radio label="0">否</el-radio>
                  <el-radio label="1">是</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 只有选择红娘角色时才显示红娘信息 -->
        <div v-if="form.userRole === '2'">
          <el-divider content-position="center" style="margin-top: 30px;">红娘信息</el-divider>
        </div>
        <el-table v-if="form.userRole === '2'" :data="tbMatchmakerList" :row-class-name="rowTbMatchmakerIndex" ref="tbMatchmaker" class="vertical-layout-table" :show-header="false" style="border: 1px solid #ebeef5; border-radius: 6px;">
          <el-table-column label="字段" width="120" align="right" class-name="field-label-column">
            <template #default="scope">
              <div style="font-weight: 500; color: #606266; padding-right: 10px;">{{ getFieldLabel(scope.$index) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="值" min-width="300" class-name="field-value-column">
            <template #default="scope">
              <!-- 真实姓名 -->
              <div v-if="scope.$index === 0">
                <el-input v-model="scope.row[scope.row.field]" placeholder="请输入真实姓名"
                          @blur="validateMatchmakerRealName(scope.row[scope.row.field], scope.$index)" />
                <div v-if="matchmakerValidationMessages[scope.$index]"
                     :class="matchmakerValidationClasses[scope.$index]"
                     style="font-size: 12px; margin-top: 4px;">
                  {{ matchmakerValidationMessages[scope.$index] }}
                </div>
              </div>
              <!-- 身份证号 -->
              <div v-else-if="scope.$index === 1">
                <el-input v-model="scope.row[scope.row.field]" placeholder="请输入身份证号"
                          @blur="validateMatchmakerIdCard(scope.row[scope.row.field], scope.$index)" />
                <div v-if="matchmakerValidationMessages[scope.$index]"
                     :class="matchmakerValidationClasses[scope.$index]"
                     style="font-size: 12px; margin-top: 4px;">
                  {{ matchmakerValidationMessages[scope.$index] }}
                </div>
              </div>
              <!-- 联系电话 -->
              <div v-else-if="scope.$index === 2">
                <el-input v-model="scope.row[scope.row.field]" placeholder="请输入联系电话"
                          @blur="validateMatchmakerPhone(scope.row[scope.row.field], scope.$index)" />
                <div v-if="matchmakerValidationMessages[scope.$index]"
                     :class="matchmakerValidationClasses[scope.$index]"
                     style="font-size: 12px; margin-top: 4px;">
                  {{ matchmakerValidationMessages[scope.$index] }}
                </div>
              </div>
              <el-select v-else-if="scope.$index === 3" v-model="scope.row[scope.row.field]" placeholder="请选择红娘等级" style="width: 100%">
                <el-option label="预备红娘" value="1" />
                <el-option label="正式红娘" value="2" />
                <el-option label="金牌红娘" value="3" />
              </el-select>
              <el-input v-else-if="scope.$index === 4" v-model="scope.row[scope.row.field]" placeholder="请输入服务区域" />
              <el-input v-else-if="scope.$index === 5" v-model="scope.row[scope.row.field]" placeholder="请输入从业年限" />
              <el-input v-else-if="scope.$index === 6" v-model="scope.row[scope.row.field]" type="textarea" placeholder="请输入个人介绍" />
              <div v-else-if="scope.$index === 7">
                <image-upload v-model="scope.row[scope.row.field]" :limit="2" :file-size="5" :is-show-tip="false"/>
                <div class="upload-tip">
                  <span style="color: #909399; font-size: 12px;">
                    请上传资质证书正面和反面照片，最多2张，每张不超过5MB
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看红娘详细信息对话框 -->
    <el-dialog title="红娘详细信息" v-model="matchmakerDetailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="真实姓名">
          {{ matchmakerDetail.realName || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="身份证号">
          {{ matchmakerDetail.idCardNo || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ matchmakerDetail.phone || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="红娘等级">
          <el-tag v-if="matchmakerDetail.matchmakerLevel === 1" type="info">预备红娘</el-tag>
          <el-tag v-else-if="matchmakerDetail.matchmakerLevel === 2" type="success">正式红娘</el-tag>
          <el-tag v-else-if="matchmakerDetail.matchmakerLevel === 3" type="warning">金牌红娘</el-tag>
          <span v-else>暂无</span>
        </el-descriptions-item>
        <el-descriptions-item label="服务区域">
          {{ matchmakerDetail.serviceArea || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="从业年限">
          {{ matchmakerDetail.serviceYears ? matchmakerDetail.serviceYears + '年' : '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="成功牵线次数">
          {{ matchmakerDetail.successCount || '0' }}次
        </el-descriptions-item>
        <el-descriptions-item label="红娘状态">
          <el-tag v-if="matchmakerDetail.matchmakerStatus === 0" type="danger">冻结</el-tag>
          <el-tag v-else-if="matchmakerDetail.matchmakerStatus === 1" type="success">正常</el-tag>
          <span v-else>暂无</span>
        </el-descriptions-item>
        <el-descriptions-item label="个人介绍" :span="2">
          {{ matchmakerDetail.introduction || '暂无个人介绍' }}
        </el-descriptions-item>
        <el-descriptions-item label="资质证书" :span="2">
          <div v-if="getCertificationImages(matchmakerDetail.certification).length > 0" class="certification-images">
            <el-image
              v-for="(img, index) in getCertificationImages(matchmakerDetail.certification)"
              :key="index"
              :src="img"
              style="width: 200px; height: 150px; margin-right: 10px; margin-bottom: 10px;"
              :preview-src-list="getCertificationImages(matchmakerDetail.certification)"
              fit="cover"
            />
            <div class="certification-labels">
              <span v-for="(img, index) in getCertificationImages(matchmakerDetail.certification)" :key="'label-' + index"
                    style="display: inline-block; width: 200px; margin-right: 10px; text-align: center; color: #666; font-size: 12px;">
                {{ index === 0 ? '资质证书正面' : index === 1 ? '资质证书反面' : `证件${index + 1}` }}
              </span>
            </div>
          </div>
          <span v-else>暂无资质证书</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ parseTime(matchmakerDetail.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          <span v-if="matchmakerDetail.updatedAt">
            {{ parseTime(matchmakerDetail.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else style="color: #909399;">暂无</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="matchmakerDetailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {
  listUser, getUser, delUser, addUser, updateUser,
  checkPhoneUnique, checkNicknameUnique, checkPasswordFormat,
  checkMatchmakerRealNameUnique, checkMatchmakerIdCardUnique, checkMatchmakerPhoneUnique
} from "@/api/user/user"
import { View } from '@element-plus/icons-vue'
import { isExternal } from "@/utils/validate"

const { proxy } = getCurrentInstance()

const userList = ref([])
const tbMatchmakerList = ref([])
const userInfoList = ref([])
const userStatusList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedTbMatchmaker = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const matchmakerDetailOpen = ref(false)
const matchmakerDetail = ref({})

// 验证相关的响应式变量
const phoneValidationMessage = ref('')
const phoneValidationClass = ref('')
const passwordValidationMessage = ref('')
const passwordValidationClass = ref('')
const nicknameValidationMessage = ref('')
const nicknameValidationClass = ref('')
const matchmakerValidationMessages = ref({})
const matchmakerValidationClasses = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: null,
    password: null,
    nickname: null,
    gender: null,
    birthDate: null,
    avatarUrl: null,
    fan: null,
    countFollow: null,
    countLike: null,
    userRole: null,
    registerSource: null,
    openId: null,
    registerTime: null,
    lastLoginTime: null,
    lastLoginIp: null,
    accountStatus: null,
    isVerified: null,
    isVip: null,
    vipExpireTime: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确，必须是11位", trigger: "blur" },
      { validator: validatePhoneUnique, trigger: "blur" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" },
      { min: 6, message: "密码不能少于6位", trigger: "blur" }
    ],
    nickname: [
      { required: true, message: "昵称不能为空", trigger: "blur" },
      { validator: validateNicknameUnique, trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    userRole: [
      { required: true, message: "用户角色不能为空", trigger: "change" }
    ],
    registerSource: [
      { required: true, message: "注册来源不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 验证手机号唯一性 */
async function validatePhoneUnique(rule, value, callback) {
  if (!value) {
    callback()
    return
  }

  try {
    // 如果是修改操作且手机号没有变化，跳过验证
    if (form.value.userId && form.value.phone === value) {
      callback()
      return
    }

    const response = await listUser({ phone: value })
    if (response.rows && response.rows.length > 0) {
      callback(new Error('手机号已存在'))
    } else {
      callback()
    }
  } catch (error) {
    callback()
  }
}

/** 验证昵称唯一性 */
async function validateNicknameUnique(rule, value, callback) {
  if (!value) {
    callback()
    return
  }

  try {
    // 如果是修改操作且昵称没有变化，跳过验证
    if (form.value.userId && form.value.nickname === value) {
      callback()
      return
    }

    const response = await listUser({ nickname: value })
    if (response.rows && response.rows.length > 0) {
      callback(new Error('昵称已存在'))
    } else {
      callback()
    }
  } catch (error) {
    callback()
  }
}

/** 查询管理用户列表 */
function getList() {
  loading.value = true
  listUser(queryParams.value).then(response => {
    userList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    phone: null,
    password: null,
    nickname: null,
    gender: null,
    birthDate: null,
    avatarUrl: null,
    fan: null,
    countFollow: null,
    countLike: null,
    userRole: "1", // 默认选择普通用户
    registerSource: null,
    openId: null,
    registerTime: null,
    lastLoginTime: null,
    lastLoginIp: null,
    accountStatus: "1", // 默认正常
    isVerified: "1", // 默认已实名认证
    isVip: "0", // 默认非VIP
    vipExpireTime: null,
    createdAt: null,
    updatedAt: null
  }
  tbMatchmakerList.value = []
  // 初始化用户信息列表
  userInfoList.value = [
    { field: 'phone' },
    { field: 'password' },
    { field: 'nickname' },
    { field: 'gender' },
    { field: 'birthDate' },
    { field: 'avatarUrl' },
    { field: 'userRole' },
    { field: 'registerSource' },
    { field: 'openId' }
  ]
  // 初始化用户状态列表
  userStatusList.value = [
    { field: 'accountStatus' },
    { field: 'isVerified' },
    { field: 'isVip' }
  ]
  // 默认选择红娘角色时，初始化红娘信息
  handleAddTbMatchmaker()

  // 清空验证信息
  phoneValidationMessage.value = ''
  phoneValidationClass.value = ''
  passwordValidationMessage.value = ''
  passwordValidationClass.value = ''
  nicknameValidationMessage.value = ''
  nicknameValidationClass.value = ''
  matchmakerValidationMessages.value = {}
  matchmakerValidationClasses.value = {}

  proxy.resetForm("userRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加管理用户"
}

/** 查看红娘详细信息 */
function handleViewMatchmaker(row) {
  const _userId = row.userId
  getUser(_userId).then(response => {
    if (response.data.tbMatchmakerList && response.data.tbMatchmakerList.length > 0) {
      matchmakerDetail.value = response.data.tbMatchmakerList[0]
    } else {
      matchmakerDetail.value = {}
      proxy.$modal.msgWarning("该用户暂无红娘信息")
      return
    }
    matchmakerDetailOpen.value = true
  }).catch(() => {
    proxy.$modal.msgError("获取红娘信息失败")
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _userId = row.userId || ids.value
  getUser(_userId).then(response => {
    console.log('获取用户数据:', response.data)
    form.value = response.data

    // 转换数字字段为字符串，确保单选框正确回显
    if (form.value.gender !== null && form.value.gender !== undefined) {
      form.value.gender = String(form.value.gender)
    }
    if (form.value.userRole !== null && form.value.userRole !== undefined) {
      form.value.userRole = String(form.value.userRole)
    }
    if (form.value.registerSource !== null && form.value.registerSource !== undefined) {
      form.value.registerSource = String(form.value.registerSource)
    }
    if (form.value.accountStatus !== null && form.value.accountStatus !== undefined) {
      form.value.accountStatus = String(form.value.accountStatus)
    }
    if (form.value.isVerified !== null && form.value.isVerified !== undefined) {
      form.value.isVerified = String(form.value.isVerified)
    }
    if (form.value.isVip !== null && form.value.isVip !== undefined) {
      form.value.isVip = String(form.value.isVip)
    }

    // 如果有红娘信息，将其转换为竖向显示格式
    if (response.data.tbMatchmakerList && response.data.tbMatchmakerList.length > 0) {
      const matchmaker = response.data.tbMatchmakerList[0]
      console.log('红娘数据:', matchmaker)
      tbMatchmakerList.value = [
        { realName: matchmaker.realName || "", field: "realName" },
        { idCardNo: matchmaker.idCardNo || "", field: "idCardNo" },
        { phone: matchmaker.phone || "", field: "phone" },
        { matchmakerLevel: String(matchmaker.matchmakerLevel || ""), field: "matchmakerLevel" },
        { serviceArea: matchmaker.serviceArea || "", field: "serviceArea" },
        { serviceYears: matchmaker.serviceYears || "", field: "serviceYears" },
        { introduction: matchmaker.introduction || "", field: "introduction" },
        { certification: matchmaker.certification || "", field: "certification" }
      ]
      console.log('转换后的红娘数据:', tbMatchmakerList.value)
    } else {
      console.log('没有红娘数据')
      tbMatchmakerList.value = []
    }
    open.value = true
    title.value = "修改管理用户"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      // 检查是否有校验错误
      if (hasValidationErrors()) {
        proxy.$modal.msgError("请先解决表单中的校验错误")
        return
      }

      // 转换字符串字段为数字，确保后端接收正确的数据类型
      const submitData = { ...form.value }

      // 转换数字字段
      if (submitData.gender !== null && submitData.gender !== undefined && submitData.gender !== '') {
        submitData.gender = parseInt(submitData.gender)
      }
      if (submitData.userRole !== null && submitData.userRole !== undefined && submitData.userRole !== '') {
        submitData.userRole = parseInt(submitData.userRole)
      }
      if (submitData.registerSource !== null && submitData.registerSource !== undefined && submitData.registerSource !== '') {
        submitData.registerSource = parseInt(submitData.registerSource)
      }
      if (submitData.accountStatus !== null && submitData.accountStatus !== undefined && submitData.accountStatus !== '') {
        submitData.accountStatus = parseInt(submitData.accountStatus)
      }
      if (submitData.isVerified !== null && submitData.isVerified !== undefined && submitData.isVerified !== '') {
        submitData.isVerified = parseInt(submitData.isVerified)
      }
      if (submitData.isVip !== null && submitData.isVip !== undefined && submitData.isVip !== '') {
        submitData.isVip = parseInt(submitData.isVip)
      }

      // 将竖向格式的红娘信息转换回原始格式
      if (tbMatchmakerList.value && tbMatchmakerList.value.length > 0) {
        const matchmaker = {}
        tbMatchmakerList.value.forEach(item => {
          const fieldName = item.field
          const fieldValue = item[fieldName]

          if (fieldName === 'realName') matchmaker.realName = fieldValue
          else if (fieldName === 'idCardNo') matchmaker.idCardNo = fieldValue
          else if (fieldName === 'phone') matchmaker.phone = fieldValue
          else if (fieldName === 'matchmakerLevel') matchmaker.matchmakerLevel = parseInt(fieldValue) || null
          else if (fieldName === 'serviceArea') matchmaker.serviceArea = fieldValue
          else if (fieldName === 'serviceYears') matchmaker.serviceYears = parseInt(fieldValue) || null
          else if (fieldName === 'introduction') matchmaker.introduction = fieldValue
          else if (fieldName === 'certification') matchmaker.certification = fieldValue
        })

        // 设置默认值
        matchmaker.successCount = 0 // 默认成功牵线次数为0
        matchmaker.matchmakerStatus = 1 // 默认红娘状态为正常

        submitData.tbMatchmakerList = [matchmaker]
      } else {
        submitData.tbMatchmakerList = []
      }
      if (submitData.userId != null) {
        updateUser(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          // 处理校验错误
          if (error.response && error.response.data && error.response.data.msg) {
            proxy.$modal.msgError(error.response.data.msg)
          } else {
            proxy.$modal.msgError("修改失败")
          }
        })
      } else {
        addUser(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          // 处理校验错误
          if (error.response && error.response.data && error.response.data.msg) {
            proxy.$modal.msgError(error.response.data.msg)
          } else {
            proxy.$modal.msgError("新增失败")
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value
  proxy.$modal.confirm('是否确认删除管理用户编号为"' + _userIds + '"的数据项？').then(function() {
    return delUser(_userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 红娘信息序号 */
function rowTbMatchmakerIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 获取字段标签 */
function getFieldLabel(index) {
  const labels = [
    '真实姓名：',
    '身份证号：',
    '联系电话：',
    '红娘等级：',
    '服务区域：',
    '从业年限：',
    '个人介绍：',
    '资质证书URL：'
  ]
  return labels[index] || ''
}

/** 获取用户信息字段标签 */
function getUserFieldLabel(index) {
  const labels = [
    '手机号：',
    '密码：',
    '昵称：',
    '性别：',
    '出生日期：',
    '头像URL：',
    '用户角色：',
    '注册来源：',
    '第三方平台ID：'
  ]
  return labels[index] || ''
}

/** 获取用户状态字段标签 */
function getUserStatusFieldLabel(index) {
  const labels = [
    '账号状态：',
    '是否实名认证：',
    '是否VIP：'
  ]
  return labels[index] || ''
}

/** 格式化日期时间 */
function formatDateTime(dateTime) {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/** 获取资质证书图片列表 */
function getCertificationImages(certification) {
  if (!certification) return []

  // 如果是字符串，按逗号分割
  if (typeof certification === 'string') {
    return certification.split(',').filter(img => img.trim() !== '').map(img => {
      const trimmedImg = img.trim()
      // 如果是外部链接，直接返回
      if (isExternal(trimmedImg)) {
        return trimmedImg
      }
      // 如果不是完整URL，添加基础URL
      return import.meta.env.VITE_APP_BASE_API + trimmedImg
    })
  }

  // 如果是数组，直接处理
  if (Array.isArray(certification)) {
    return certification.filter(img => img && img.trim() !== '').map(img => {
      const trimmedImg = img.trim()
      if (isExternal(trimmedImg)) {
        return trimmedImg
      }
      return import.meta.env.VITE_APP_BASE_API + trimmedImg
    })
  }

  return []
}

/** 用户角色变化处理 */
function handleUserRoleChange(value) {
  if (value === '2') {
    // 选择红娘角色，初始化红娘信息
    if (!tbMatchmakerList.value || tbMatchmakerList.value.length === 0) {
      handleAddTbMatchmaker()
    }
  } else {
    // 选择普通用户，清空红娘信息
    tbMatchmakerList.value = []
  }
}

/** 手机号变化处理 */
function handlePhoneChange() {
  // 如果输入了手机号，自动选择注册来源为手机号
  if (form.value.phone && form.value.phone.length === 11) {
    form.value.registerSource = '1'
  }
}

/** 验证手机号 */
async function validatePhone() {
  if (!form.value.phone) {
    phoneValidationMessage.value = ''
    phoneValidationClass.value = ''
    return
  }

  try {
    const response = await checkPhoneUnique(form.value.phone, form.value.userId)
    if (response.code === 200) {
      phoneValidationMessage.value = response.msg || '手机号可以使用'
      phoneValidationClass.value = 'color: #67c23a;'
    } else {
      phoneValidationMessage.value = response.msg
      phoneValidationClass.value = 'color: #f56c6c;'
    }
  } catch (error) {
    phoneValidationMessage.value = '验证失败，请重试'
    phoneValidationClass.value = 'color: #f56c6c;'
  }
}

/** 验证密码 */
async function validatePassword() {
  if (!form.value.password) {
    passwordValidationMessage.value = ''
    passwordValidationClass.value = ''
    return
  }

  try {
    const response = await checkPasswordFormat(form.value.password)
    if (response.code === 200) {
      passwordValidationMessage.value = response.msg || '密码格式正确'
      passwordValidationClass.value = 'color: #67c23a;'
    } else {
      passwordValidationMessage.value = response.msg
      passwordValidationClass.value = 'color: #f56c6c;'
    }
  } catch (error) {
    passwordValidationMessage.value = '验证失败，请重试'
    passwordValidationClass.value = 'color: #f56c6c;'
  }
}

/** 验证昵称 */
async function validateNickname() {
  if (!form.value.nickname) {
    nicknameValidationMessage.value = ''
    nicknameValidationClass.value = ''
    return
  }

  try {
    const response = await checkNicknameUnique(form.value.nickname, form.value.userId)
    if (response.code === 200) {
      nicknameValidationMessage.value = response.msg || '昵称可以使用'
      nicknameValidationClass.value = 'color: #67c23a;'
    } else {
      nicknameValidationMessage.value = response.msg
      nicknameValidationClass.value = 'color: #f56c6c;'
    }
  } catch (error) {
    nicknameValidationMessage.value = '验证失败，请重试'
    nicknameValidationClass.value = 'color: #f56c6c;'
  }
}

/** 验证红娘真实姓名唯一性 */
async function validateMatchmakerRealName(value, index) {
  if (!value) {
    matchmakerValidationMessages.value[index] = ''
    matchmakerValidationClasses.value[index] = ''
    return
  }

  try {
    const response = await checkMatchmakerRealNameUnique(value, form.value.userId)
    if (response.code === 200) {
      matchmakerValidationMessages.value[index] = response.msg || '真实姓名可以使用'
      matchmakerValidationClasses.value[index] = 'color: #67c23a;'
    } else {
      matchmakerValidationMessages.value[index] = response.msg
      matchmakerValidationClasses.value[index] = 'color: #f56c6c;'
    }
  } catch (error) {
    matchmakerValidationMessages.value[index] = '验证失败，请重试'
    matchmakerValidationClasses.value[index] = 'color: #f56c6c;'
  }
}

/** 验证红娘身份证号唯一性 */
async function validateMatchmakerIdCard(value, index) {
  if (!value) {
    matchmakerValidationMessages.value[index] = ''
    matchmakerValidationClasses.value[index] = ''
    return
  }

  try {
    const response = await checkMatchmakerIdCardUnique(value, form.value.userId)
    if (response.code === 200) {
      matchmakerValidationMessages.value[index] = response.msg || '身份证号可以使用'
      matchmakerValidationClasses.value[index] = 'color: #67c23a;'
    } else {
      matchmakerValidationMessages.value[index] = response.msg
      matchmakerValidationClasses.value[index] = 'color: #f56c6c;'
    }
  } catch (error) {
    matchmakerValidationMessages.value[index] = '验证失败，请重试'
    matchmakerValidationClasses.value[index] = 'color: #f56c6c;'
  }
}

/** 验证红娘联系电话 */
async function validateMatchmakerPhone(value, index) {
  if (!value) {
    matchmakerValidationMessages.value[index] = ''
    matchmakerValidationClasses.value[index] = ''
    return
  }

  try {
    const response = await checkMatchmakerPhoneUnique(value, form.value.userId)
    if (response.code === 200) {
      matchmakerValidationMessages.value[index] = response.msg || '联系电话可以使用'
      matchmakerValidationClasses.value[index] = 'color: #67c23a;'
    } else {
      matchmakerValidationMessages.value[index] = response.msg
      matchmakerValidationClasses.value[index] = 'color: #f56c6c;'
    }
  } catch (error) {
    matchmakerValidationMessages.value[index] = '验证失败，请重试'
    matchmakerValidationClasses.value[index] = 'color: #f56c6c;'
  }
}

/** 检查是否有校验错误 */
function hasValidationErrors() {
  // 检查基本信息校验错误
  if (phoneValidationClass.value.includes('f56c6c') ||
      passwordValidationClass.value.includes('f56c6c') ||
      nicknameValidationClass.value.includes('f56c6c')) {
    return true
  }

  // 如果用户角色是红娘，检查红娘信息是否完整
  if (form.value.userRole === '2') {
    if (!tbMatchmakerList.value || tbMatchmakerList.value.length === 0) {
      proxy.$modal.msgError("红娘角色必须填写红娘信息")
      return true
    }

    // 检查红娘必填字段
    const requiredFields = ['realName', 'idCardNo', 'phone']
    for (const item of tbMatchmakerList.value) {
      if (requiredFields.includes(item.field) && !item[item.field]) {
        proxy.$modal.msgError(`请填写红娘${getFieldLabel(tbMatchmakerList.value.indexOf(item)).replace('：', '')}`)
        return true
      }
    }

    // 检查红娘信息校验错误
    for (const key in matchmakerValidationClasses.value) {
      if (matchmakerValidationClasses.value[key].includes('f56c6c')) {
        return true
      }
    }
  }

  return false
}

/** 红娘信息添加按钮操作 */
function handleAddTbMatchmaker() {
  // 创建一个包含所有字段的数组，每个字段作为一行
  const matchmakerFields = [
    { realName: "", field: "realName" },
    { idCardNo: "", field: "idCardNo" },
    { phone: "", field: "phone" },
    { matchmakerLevel: "", field: "matchmakerLevel" }, // 不设置默认值
    { serviceArea: "", field: "serviceArea" },
    { serviceYears: "", field: "serviceYears" },
    { introduction: "", field: "introduction" },
    { certification: "", field: "certification" }
  ]

  // 将字段数组添加到列表中
  tbMatchmakerList.value = matchmakerFields
}

/** 红娘信息删除按钮操作 */
function handleDeleteTbMatchmaker() {
  if (checkedTbMatchmaker.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的红娘信息数据")
  } else {
    const tbMatchmakers = tbMatchmakerList.value
    const checkedTbMatchmakers = checkedTbMatchmaker.value
    tbMatchmakerList.value = tbMatchmakers.filter(function(item) {
      return checkedTbMatchmakers.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleTbMatchmakerSelectionChange(selection) {
  checkedTbMatchmaker.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('user/user/export', {
    ...queryParams.value
  }, `user_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.vertical-layout-table {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.vertical-layout-table .el-table__body-wrapper {
  border-radius: 6px;
}

.vertical-layout-table .el-table__row {
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.vertical-layout-table .el-table__row:hover {
  background-color: #fafafa;
}

.vertical-layout-table .el-table__row:last-child {
  border-bottom: none;
}

.vertical-layout-table .el-table__cell {
  padding: 15px 12px;
  vertical-align: top;
}

.vertical-layout-table .field-label-column {
  background-color: #f8f9fa;
  border-right: 1px solid #e9ecef;
  width: 120px;
}

.vertical-layout-table .field-label-column div {
  font-weight: 500;
  color: #495057;
  text-align: right;
  padding-right: 8px;
}

.vertical-layout-table .field-value-column {
  background-color: #ffffff;
}

.upload-tip {
  margin-top: 8px;
  line-height: 1.4;
  text-align: center;
}

.upload-tip span {
  display: inline-block;
  color: #6c757d;
  font-size: 12px;
}

/* 表单项间距优化 */
.el-form-item {
  margin-bottom: 20px;
}

/* 分割线样式优化 */
.el-divider {
  margin: 24px 0 20px 0;
}

.el-divider__text {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

/* 输入框样式优化 */
.el-input, .el-select {
  border-radius: 4px;
}

.el-textarea .el-textarea__inner {
  border-radius: 4px;
  min-height: 80px;
}

/* 单选框组样式优化 */
.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.el-radio {
  margin-right: 0;
}

.certification-images {
  display: flex;
  flex-direction: column;
}

.certification-images .el-image {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.certification-images .el-image:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.certification-labels {
  margin-top: 5px;
}
</style>
